package com.example.receiptmanage.service;

import com.example.receiptmanage.dto.ReceiptInfoDTO;
import com.example.receiptmanage.dto.WeeklyExpenseDTO;
import com.example.receiptmanage.entity.ReceiptData;
import com.example.receiptmanage.entity.Receipts;
import com.example.receiptmanage.repository.ReceiptDataRepository;
import com.example.receiptmanage.repository.ReceiptRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReceiptService {

    @Autowired
    private ReceiptRepository receiptRepository;
    @Autowired
    private ReceiptDataRepository receiptDataRepository;


    public List<ReceiptInfoDTO> getRecentReceiptsByUserId(Long userId) {
        List<Receipts> receipts = receiptRepository.findByUserIdOrderByReceiptDateDesc(userId);

        List<ReceiptInfoDTO> dtos = new ArrayList<>();
        for (Receipts receipt : receipts) {
            ReceiptInfoDTO dto = new ReceiptInfoDTO();
            BeanUtils.copyProperties(receipt, dto); // 拷贝主表字段

            // 查询子表数据
            List<ReceiptData> dataList = receiptDataRepository.findByReceiptId(receipt.getReceiptId());
            dto.setReceiptDataList(dataList);

            dtos.add(dto);
        }
        return dtos;
    }


    public List<WeeklyExpenseDTO> getWeeklyExpenses(Long userId) {
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(6);

        List<Receipts> receipts = receiptRepository.findByUserIdAndReceiptDateBetween(
                userId, startDate, endDate);

        // 使用 Double 类型而不是 BigDecimal
        Map<LocalDate, Double> dailyExpenses = new TreeMap<>();
        for (int i = 0; i < 7; i++) {
            dailyExpenses.put(startDate.plusDays(i), 0.0);
        }

        for (Receipts receipt : receipts) {
            LocalDate date = receipt.getReceiptDate();
            Double amount = receipt.getTotalAmount() != null ? receipt.getTotalAmount() : 0.0;
            dailyExpenses.merge(date, amount, Double::sum);
        }

        return dailyExpenses.entrySet().stream()
                .map(entry -> new WeeklyExpenseDTO(
                        entry.getKey().format(DateTimeFormatter.ISO_DATE),
                        entry.getValue()
                ))
                .collect(Collectors.toList());
    }

    // 获取单个票据
    public Optional<Receipts> getReceiptByIdAndUserId(Long receiptId, Long userId) {
        return receiptRepository.findByReceiptIdAndUserId(receiptId, userId);
    }
    
    // 更新票据
    public Receipts updateReceipt(Receipts receipt) {
        return receiptRepository.save(receipt);
    }
}